function [ww,uu,vv,num_loop] = alg_WMMSE(N,K,MG,hGG,noise,pow_max)
ww = initialize_w(N,K,MG,hGG,pow_max);
sum_rate_terres_record = [];
sum_rate_terres_old = 1e-10;
% vv_conver_record = [];
% vv_conver_old = 1e-10;
num_loop=0;
while true
    %% update U V W
    uu = update_u_WMMSE(N,K,ww,hGG,noise);
    vv = zeros(N,K);% complex !!!!!!!!!
    for nn=1:N
        for kk=1:K
            vv(nn,kk) = 1/(1 - uu(nn,kk)' * hGG{nn,nn,kk}'*ww(:,nn,kk));
        end
    end
    [ww,eta]=update_w_WMMSE_bisection(N,K,MG,hGG,uu,vv,pow_max);
    num_loop=num_loop+1;

    %% converge?????????????
    sum_rate_terres = cal_sum_rate_terres(N,K,ww,hGG,noise);
    sum_rate_terres_record = [sum_rate_terres_record;sum_rate_terres]; % 用于绘图
    if abs(sum_rate_terres-sum_rate_terres_old) / sum_rate_terres_old < 0.01
        fprintf('WMMSE terminates: sum_rate_terres converges\n');
        break
    else
        sum_rate_terres_old = sum_rate_terres;
    end
    
%     vv_conver = sum(sum(log(abs(vv))));
%     vv_conver_record = [vv_conver_record;vv_conver];    % 用于绘图
%     if abs(vv_conver-vv_conver_old) / vv_conver_old < 1e-10
%         fprintf('WMMSE terminates: f_quadratic converges\n');
%         break
%     else
%         vv_conver_old = vv_conver;
%     end
end

ff=figure;
plot(1:length(sum_rate_terres_record),sum_rate_terres_record,'o-');hold on
ylabel('Sum rate (bps/Hz)')
% ylabel('sum_rate_terres')
% plot(1:length(vv_conver_record),vv_conver_record,'o-');hold on
% ylabel('vv_conver')
grid on
xlabel('The number of iterations of WMMSE')
set(gca, 'FontName', 'Times New Roman','FontSize',12)
set(ff,'Position',[1200,300,500,400]);
end






function uu = update_u_WMMSE(N,K,ww,hGG,noise)
% update u_{n,k}
uu=zeros(N,K);% real !!!!!!!!!
for nn=1:N
    for kk=1:K
        temptemp = 0;
        for mm=1:N
            for ll=1:K
                temptemp = temptemp + abs(ww(:,mm,ll)'*hGG{mm,nn,kk})^2;
            end
        end
        uu(nn,kk) = hGG{nn,nn,kk}'*ww(:,nn,kk) / (noise + temptemp);
    end
end
end

